import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import { App } from 'vue';
import { AppRouteRecordRaw } from '@/router/types';
/* Layout */
import Layout from '@/layout/index.vue';
import { setupLayouts } from 'virtual:generated-layouts';
// 导入自动生成的路由（unplugin-vue-router）
// import { routes as autoRoutes } from 'vue-router/auto-routes';

import generatedRoutes from 'virtual:generated-pages';

// 白名单
const WHITE_LIST = ['/login', '/register', '/wxLoginPage'];

// 直接使用 generatedRoutes，不再需要预处理
// console.log(generatedRoutes, 'generatedRoutes');

/**
 * 创建安全的前台路由，使用 setupLayouts 但避免只读属性错误
 * @description 使用 setupLayouts 但通过深拷贝确保安全性
 */
function createSafeReceptionRoutes() {
  try {
    const safeRoutes = generatedRoutes.map((route: any) => {
      // 确保每个路由都有完整的 meta 信息
      route.meta = {
        title: route.meta?.title || '页面',
        layout: route.meta?.layout || 'pc-default',
        requiresAuth: false,
        isAdmin: false,
        icon: 'dashboard',
        hidden: false,
        ...route.meta,
      };

      // 重新绑定组件引用（JSON 序列化会丢失函数引用）
      const originalRoute = generatedRoutes.find((r: any) => r.path === route.path);
      if (originalRoute) {
        route.component = originalRoute.component;

        // 处理子路由的组件引用
        if (route.children && originalRoute.children) {
          route.children.forEach((child: any, index: number) => {
            if (originalRoute.children && originalRoute.children[index]) {
              child.component = originalRoute.children[index].component;
            }
          });
        }
      }

      return route;
    });

    // 使用 setupLayouts 处理布局
    const layoutRoutes = setupLayouts(safeRoutes);

    console.log('使用 setupLayouts 处理的前台路由:', layoutRoutes);
    return layoutRoutes as AppRouteRecordRaw[];
  } catch (error) {
    console.warn('创建前台路由时发生错误:', error);
    // 如果 setupLayouts 失败，返回空数组
    return [] as AppRouteRecordRaw[];
  }
}

// 前台动态生成相关页面路由
export const receptionDesk: AppRouteRecordRaw[] = createSafeReceptionRoutes();

export { WHITE_LIST };
// 公共路由
export const constantRoutes: AppRouteRecordRaw[] = [
  // 前台路由 - 使用布局包装器
  ...receptionDesk,
  // 后台重定向首页
  {
    path: '/index',
    component: Layout,
    hidden: true,
    redirect: '/index/dashboard',
    children: [
      {
        path: '/index/dashboard',
        component: () => import('@/views/index.vue'),
        name: 'Index',
        hidden: true,
        meta: {
          title: '首页',
          icon: 'dashboard',
          affix: true,
          isAdmin: true,
        },
      },
    ],
  },

  {
    path: '/redirect',
    component: Layout,
    hidden: true,
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/index.vue'),
      },
    ],
  },
  {
    path: '/login',
    component: () => import('@/views/login.vue'),
    hidden: true,
  },
  {
    path: '/register',
    component: () => import('@/views/register.vue'),
    hidden: true,
  },

  {
    path: '/:pathMatch(.*)*',
    component: () => import('@/views/error/404.vue'),
    hidden: true,
  },
  {
    path: '/401',
    component: () => import('@/views/error/401.vue'),
    hidden: true,
  },
  {
    path: '/user',
    component: Layout,
    hidden: true,
    redirect: 'noredirect',
    children: [
      {
        path: 'profile',
        component: () => import('@/views/system/user/profile/index.vue'),
        name: 'Profile',
        meta: { title: '个人中心', icon: 'user' },
      },
    ],
  },
];

// 动态路由，基于用户权限动态去加载
export const dynamicRoutes: AppRouteRecordRaw[] = [
  {
    path: '/system/user-auth',
    component: Layout,
    hidden: true,
    permissions: ['system:user:edit'],
    children: [
      {
        path: 'role/:userId(\\d+)',
        component: () => import('@/views/system/user/authRole.vue'),
        name: 'AuthRole',
        meta: { title: '分配角色', activeMenu: '/system/user' },
      },
    ],
  },
  {
    path: '/system/role-auth',
    component: Layout,
    hidden: true,
    permissions: ['system:role:edit'],
    children: [
      {
        path: 'user/:roleId(\\d+)',
        component: () => import('@/views/system/role/authUser.vue'),
        name: 'AuthUser',
        meta: { title: '分配用户', activeMenu: '/system/role' },
      },
    ],
  },
  {
    path: '/system/dict-data',
    component: Layout,
    hidden: true,
    permissions: ['system:dict:list'],
    children: [
      {
        path: 'index/:dictId(\\d+)',
        component: () => import('@/views/system/dict/data.vue'),
        name: 'Data',
        meta: { title: '字典数据', activeMenu: '/system/dict' },
      },
    ],
  },
  {
    path: '/monitor/job-log',
    component: Layout,
    hidden: true,
    permissions: ['monitor:job:list'],
    children: [
      {
        path: 'index/:jobId(\\d+)',
        component: () => import('@/views/monitor/job/log.vue'),
        name: 'JobLog',
        meta: { title: '调度日志', activeMenu: '/monitor/job' },
      },
    ],
  },
  {
    path: '/tool/gen-edit',
    component: Layout,
    hidden: true,
    permissions: ['tool:gen:edit'],
    children: [
      {
        path: 'index/:tableId(\\d+)',
        component: () => import('@/views/tool/gen/editTable.vue'),
        name: 'GenEdit',
        meta: { title: '修改生成配置', activeMenu: '/tool/gen' },
      },
    ],
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes: constantRoutes.map((route) => ({ ...route })) as RouteRecordRaw[], // 确保路由对象可变
  scrollBehavior(_, __, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
  strict: false, // 关闭严格模式
});

// 添加错误处理
router.onError((error) => {
  console.error('路由错误:', error);
});

export default router;

// config router
export function setupRouter(app: App<Element>) {
  app.use(router);
}
